package com.suray.wcs.service.init.map;

import com.suray.basic.wcs.utils.LoggerUtil;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.rgv.RgvInterface;
import com.suray.wcs.service.system.entity.RgvMapDB;
import com.suray.wcs.service.system.service.impl.RgvMapDBServiceImpl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RgvMapManage {
    /**
     * 小车地图
     */
    private Map<Integer, String> rgvMapMap = new HashMap<>();

    private RgvMapDBServiceImpl rgvMapDBService = SpringContextHolder.getBean(RgvMapDBServiceImpl.class);

    public RgvMapManage() {

    }

    public Map<Integer, String> getRgvMapMap() {
        Map<Integer, String> rgvMapMap = new HashMap<>();
        rgvMapMap.putAll(this.rgvMapMap);
        return rgvMapMap;
    }

    /**
     * 加载rgv地图
     */
    public void loadRgvMaps(List<RgvMapDB> rgvMapDBS) {
        for (RgvMapDB rgvMapDB : rgvMapDBS) {
            try {
                loadRgvMap(rgvMapDB);
            } catch (Exception e) {
                LoggerUtil.error("地图加载失败:" + rgvMapDB, this.getClass());
            }
        }

        //RgvInterface.initMap(this.rgvMapMap);
    }

    /**
     * 添加小车地图
     * @param rgvMapDB
     */
    public synchronized boolean addRgvMap(RgvMapDB rgvMapDB) {
        LoggerUtil.info("添加地图：" + rgvMapDB, this.getClass());
        rgvMapMap.put(rgvMapDB.getLayer(), rgvMapDB.getMap());
        RgvInterface.addMap(rgvMapDB.getLayer(), rgvMapDB.getMap());
        return rgvMapDBService.insertWcsDist(rgvMapDB);
    }

    /**
     * 加载地图
     * @param rgvMapDB
     * @return
     */
    public synchronized boolean loadRgvMap(RgvMapDB rgvMapDB) {
        LoggerUtil.info("添加地图：" + rgvMapDB, this.getClass());
        rgvMapMap.put(rgvMapDB.getLayer(), rgvMapDB.getMap());
        RgvInterface.addMap(rgvMapDB.getLayer(), rgvMapDB.getMap());
        return true;
    }

    /**
     * 修改小车地图
     * @param oldRgvMapDB
     * @param newRgvMapDB
     */
    public synchronized int changeRgvMap(RgvMapDB oldRgvMapDB, RgvMapDB newRgvMapDB) {
        LoggerUtil.info("修改地图：" + oldRgvMapDB + " -> " + newRgvMapDB, this.getClass());
        if (!oldRgvMapDB.getLayer().equals(newRgvMapDB.getLayer())) {
            rgvMapMap.remove(oldRgvMapDB.getLayer());
            RgvInterface.deleteMap(oldRgvMapDB.getLayer());
        }
        rgvMapMap.put(newRgvMapDB.getLayer(), newRgvMapDB.getMap());
        RgvInterface.addMap(newRgvMapDB.getLayer(), newRgvMapDB.getMap());
        return rgvMapDBService.updateMap(newRgvMapDB);
    }

    /**
     * 删除小车地图
     * @param id
     */
    public synchronized boolean deleteRgvMap(long id) {
        RgvMapDB rgvMapDB = rgvMapDBService.getById(id);
        LoggerUtil.info("删除地图：" + rgvMapDB, this.getClass());
        rgvMapMap.remove(rgvMapDB.getLayer());
        RgvInterface.deleteMap(rgvMapDB.getLayer());
        return rgvMapDBService.removeByIds(Arrays.asList(id));
    }
}
